package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pojo.*;
import com.itheima.service.ClazzService;
import com.itheima.service.StudentService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/students")
public class StudentController {

    @Autowired
    private StudentService studentService;
    @Autowired
    private ClazzService clazzService;

    @GetMapping
    public Result list(StudentQueryParam student) {
        log.info("查询所有学生信息：{}", student);
        Page<Student> page = new Page<>(student.getPage(), student.getPageSize());
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(student.getName() != null && student.getName().length() > 0, Student::getName, student.getName())
                .eq(student.getDegree() != null, Student::getDegree, student.getDegree())
                .eq(student.getClazzId() != null, Student::getClazzId, student.getClazzId());
        queryWrapper.orderByDesc(Student::getUpdateTime);
        page = studentService.page(page, queryWrapper);
        List<Student> studentList = page.getRecords();
        if (studentList != null && !studentList.isEmpty()) {
            Set<Integer> clazzIds = studentList.stream().filter(student1 -> student1.getClazzId() != null).map(Student::getClazzId).collect(Collectors.toSet());
            Map<Integer, String> collect = clazzService.list(new LambdaQueryWrapper<Clazz>().in(Clazz::getId, clazzIds))
                    .stream().filter(Objects::nonNull).collect(Collectors.toMap(Clazz::getId, Clazz::getName));
            for (Student student1 : studentList) {
                student1.setClazzName(collect.get(student1.getClazzId()));
            }
        }

        return Result.success(new PageResult<>(page.getTotal(), studentList));
    }

    @PostMapping
    public Result save(@RequestBody Student student) {
        log.info("新增学生信息：{}", student);
        boolean r = studentService.saveStudent(student);
        return r ? Result.success() : Result.error("新增失败");
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        log.info("根据id查询学生信息：{}", id);
        Student student = studentService.getById(id);
        Clazz clazz = clazzService.getById(student.getClazzId());
        if (clazz != null) student.setClazzName(clazz.getName());
        return Result.success(student);
    }

    @PutMapping
    public Result update(@RequestBody Student student) {
        log.info("修改学生信息：{}", student);
        boolean r = studentService.updateStudent(student);
        return r ? Result.success() : Result.error("修改失败");
    }

    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable List<Integer> ids) {
        log.info("根据id删除学生信息：{}", ids);
        studentService.removeBatchByIds(ids);
        return Result.success();
    }

    @PutMapping("/violation/{id}/{score}")
    public Result violation(@PathVariable Integer id, @PathVariable Integer score) {
        log.info("根据id{}扣分, 扣分：{}", id, score);
        boolean r = studentService.violation(id, score);
        return r ? Result.success() : Result.error("修改失败");
    }
}
